package com.jt.demos;

import redis.clients.jedis.Jedis;

import java.util.*;

public class SSOdemo01 {

    public static boolean isValidSession (String token){
        if (token==null || "".equals(token)){
            return false;
        }
        //1. 访问redis,检查是否有有效会话信息
        Jedis jedis = new Jedis("192.168.126.129",6379);
        Map<String,String> map = jedis.hgetAll("session");
        String user = jedis.hget("session", token);
        System.out.println("user="+user);
        if(user==null){
            System.out.println("请登陆");
            jedis.close();
            return false;
        }
        //2. 判定是否登陆超时
        String dateStr = jedis.hget("session",token+":expired");
        Date expired = new Date(Long.valueOf(dateStr));
        if(dateStr==null||"".equals(dateStr)||expired.before(new Date())){
            System.out.println("登陆超时");
            jedis.close();
            return false;
        }
        return true;
    }
    public static String login(String username,String password){
        System.out.println("基于"+username+"/"+password+"进行登录");
        //1. 创建token
        String token = UUID.randomUUID().toString().replace("-", "");
        System.out.println(token);
        //2. 创建有效时长
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,30);
        //3. 存储会话信息
        Map<String,String> map = new HashMap<>();
        map.put(token, username);
        map.put(token+":expired", String.valueOf(calendar.getTimeInMillis()));
        Jedis jedis = new Jedis("192.168.126.129",6379);
        //jedis.auth("123456");
        jedis.hset("session", map);
        jedis.close();
        return token;
    }


    public static void main(String[] args) {
        System.out.println("===访问系统资源===");
        String token=null;
        boolean flag = isValidSession(token);
        System.out.println(flag?"第一次:已登录":"第一次:未登录");
        //执行登录
        if(!flag){
            System.out.print("执行登录:");
            token=login("jack","123456");
            //登录成功的这个token将来响应到客户端
        }
        //第二次访问:
        flag=isValidSession(token);
        System.out.println(flag?"第二次:已登录":"第二次:未登录");
        System.out.println(token);
        //第三次访问:
        flag=isValidSession(token);
        System.out.println(flag?"第三次:已登录":"第三次:未登录");
    }
}
